package com.bj58.groupbuy.action.controllers;


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;

import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.WanCompany;
import com.bj58.groupbuy.action.model.WanGame;
import com.bj58.groupbuy.action.model.WanOrderStat;
import com.bj58.groupbuy.action.model.WanService;
import com.bj58.groupbuy.action.service.WebGameService;
import com.bj58.groupbuy.action.util.FusionChartsUtil;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.IOUtils;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;

/**网页游戏数据统计
 * @author HL
 *
 */
@Path("game")
public class WebGameController  extends MvcController{
	private  WebGameService webGameService = ServiceLocator.get(WebGameService.class);
	private FusionChartsUtil fcu = new FusionChartsUtil();
	private SomePublicUtil spu = new SomePublicUtil();
	/**订单数据统计
	 * @return
	 */
	@Path("/orderstat")
	@GET
	@Check
	@POST
	public ActionResult orderStat(){
		HttpServletRequest  request = beat.getRequest();
		HttpServletResponse response= beat.getResponse();
		Model model = beat.getModel();
		try{
			TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
			String startDate = ServletRequestUtils.getStringParameter(request, "startDate","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate","");
			
			int companyId = ServletRequestUtils.getIntParameter(request, "companyId",0);//游戏公司
			long gameId = ServletRequestUtils.getLongParameter(request, "gameId",0);//游戏
			int type =  ServletRequestUtils.getIntParameter(request,"type",0);//查询类型   0：按天  1：按小时
			long serverId = ServletRequestUtils.getLongParameter(request, "serverId",0);//游戏
			
			String orderBy = ServletRequestUtils.getStringParameter(request, "orderBy","");//排序
			int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex",1);//页数。
			int down =  ServletRequestUtils.getIntParameter(request,"down",0);//下载标识
			
			//字段解析渲染
			List<String>  dicList  = spu.getECDicByAnnotation(WanOrderStat.class);
			model.add("dicList",dicList);
			//游戏公司列表
			List<WanCompany>  gameCompanyList = webGameService.getCompanyList();
			model.add("gameCompanyList",gameCompanyList);
			//游戏列表
			if(companyId >0 ){
				List<WanGame> gameList = webGameService.getGameList(companyId);
				model.add("gameList",gameList);
			}
			//服务器列表
			if(companyId >0 && gameId>0){
				List<WanService> serviceList = webGameService.getServiceList(companyId,gameId);
				model.add("serviceList",serviceList);
			}
			//查询
			if(!"".equals(startDate) && !"".equals(endDate)){
				StringBuffer url =new StringBuffer();//分页的URL
				//查询where条件
				StringBuffer  condition = new StringBuffer();
				condition.append(" and stat_date>='"+startDate+"' ");
				url.append("&startDate="+startDate);
				condition.append(" and stat_date<='"+endDate+"' ");
				url.append("&endDate="+endDate);
				
				if(companyId > 0 ){ //公司
					condition.append(" and company_id ="+companyId+" ");
					url.append("&companyId="+companyId);
				}
				if(gameId > 0 ){ //游戏
					condition.append(" and game_id ="+gameId+" ");
					url.append("&gameId="+gameId);
				}
				if(serverId>0 ){ //服务器
					condition.append(" and server_id ="+serverId+" ");
					url.append("&serverId="+serverId);
				}
				
				String order = "";//排序
				if(!"".equals(orderBy)){
					order = "order by "+orderBy+" desc";
				}else{
					if(type == 0){
						order = "order by  stat_date";
					}else{
						order = "order by  hour ";
					}
					
				}
				url.append("&orderBy="+orderBy);
				url.append("&type="+type);
				
				//查询项
				List<String> cols = new ArrayList<String>();
				if(type == 0){
					cols.add("stat_date");
				}else{
					cols.add("hour");
				}
				for(String dic : dicList){
					cols.add(dic.split(",")[0]);
				}
				
				int pageNum = 20;
				if(down == 0){
					Paginate<WanOrderStat> pList = webGameService.wanOrderStat(cols, condition.toString(), order, pageNum, pageIndex, type,0);
					
					cols.remove(0);
					Paginate<WanOrderStat> pListAll=webGameService.wanOrderStat(cols, condition.toString(), "", pageNum, pageIndex, type,1);
					WanOrderStat  countAllRecord=pListAll.getItems().get(0);
					model.add("countAllRecord",countAllRecord);
					
					model.add("pList",pList);
					model.add("rsList",pList.getItems());
					model.add("paramurl",url.toString());//分页URL
					
					StringBuffer  IndexList = new StringBuffer();
					for(int i = 0 ; i<dicList.size(); i++){
						String dic  = dicList.get(i).replace(",", ":");
						IndexList.append(dic);
						if((i+1) < dicList.size()){
							IndexList.append(";");
						}
					}
					model.add("IndexList",IndexList.toString());
				}else if(down == 1){
					pageIndex = -1;
					Paginate<WanOrderStat> pList = webGameService.wanOrderStat(cols, condition.toString(), order, pageNum, pageIndex, type,0);
					StringBuffer excelDic = new StringBuffer();
					excelDic.append("stat_date:日期;");
					excelDic.append("hour:小时;");
					for(String dic : dicList){
						excelDic.append(dic.split(",")[0]+":"+dic.split(",")[1]+";");
					}
				/*	WritableWorkbook wwb = ExcelUtil.writeExcelCommon2("游戏订单数据报表", response, cols, excelDic.toString(), pList.getItems(), WanOrderStat.class);
					ExcelUtil.downLoadExcel(request, response,"游戏订单数据报表", wwb);
			*/	}
			}
			model.add("startDate",startDate);
			model.add("endDate",endDate);
			model.add("companyId",companyId);
			model.add("gameId",gameId);
			model.add("serverId",serverId);
			model.add("orderBy",orderBy);
			model.add("pageindex",pageIndex);
			model.add("down",down);
			model.add("class",WanOrderStat.class);
			model.add("type",type);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("game/orderstat");
	}
	
	
	/**游戏订单统计-多指标单时间维度图表
	 * @return
	 */
	@SuppressWarnings("static-access")
	@Path("osmoresearch")
	@POST
	public ActionResult orderGameMoreSearch(){
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		try{	
			String pics = ServletRequestUtils.getStringParameter(request, "pics");
			String startDate = ServletRequestUtils.getStringParameter(request, "startDate","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate","");
			int companyId = ServletRequestUtils.getIntParameter(request, "companyId",0);//游戏公司
			int gameId = ServletRequestUtils.getIntParameter(request, "gameId",0);//游戏
			int type =  ServletRequestUtils.getIntParameter(request,"type",0);//查询类型   0：按天  1：按小时
			int serverId = ServletRequestUtils.getIntParameter(request, "serverId",0);//服务器
			
			//查询where条件
			StringBuffer  condition = new StringBuffer();
			condition.append(" and stat_date>='"+startDate+"' ");
			condition.append(" and stat_date<='"+endDate+"' ");
			if(companyId > 0 ){ //公司
				condition.append(" and company_id ="+companyId+" ");
			}
			if(gameId > 0 ){ //游戏
				condition.append(" and game_id ="+gameId+" ");
			}
			if(serverId>0){ //服务器
				condition.append(" and server_id ="+serverId+" ");
			}
			
			TreeMap<String,TreeMap<String,List<String>>> rsMap = new TreeMap<String,TreeMap<String,List<String>>> ();
			List<String> xAxisList = new ArrayList<String>(); //X轴集合
			TreeMap<String,List<String>> leftAxisValues = new TreeMap<String,List<String>>(); //左轴集合
			TreeMap<String,List<String>> rightAxisValues = new TreeMap<String,List<String>>();//右轴集合
			
			String order = "";//排序
			if(type == 0){
				order = "order by  stat_date";
			}else{
				order = "order by  hour ";
			}
			//查询项
			List<String> cols = new ArrayList<String>();
			if(type == 0){
				cols.add("stat_date");
			}else{
				cols.add("hour");
			}
			for(String fs : pics.split(",")){
				cols.add(fs);
			}
			Paginate<WanOrderStat> pList = webGameService.wanOrderStat(cols, condition.toString(), order, 20, -1, type,0);
			if(null == pList.getItems() ||  pList.getItems().isEmpty()){
				return new ContentResult("NODATA");
			}
			rsMap = fcu.SortingForNoExName(pics, pList.getItems(), WanOrderStat.class, request);
			for(WanOrderStat vo : pList.getItems()){
				if(type == 0){
					xAxisList.add(vo.getStat_date());
				}else{
					xAxisList.add(String.valueOf(vo.getHour()));
				}
				
			}
			rightAxisValues = rsMap.get("right");
			
			if(rsMap.size() > 1){
				leftAxisValues = rsMap.get("left");
			}
			String xml = "";
			//双Y轴数量级时
			if(leftAxisValues.size() > 0){
				xml = FusionChartsUtil.MSColumn3DLineDY(xAxisList, leftAxisValues, rightAxisValues);
				xml = "LINEDY:"+xml;
			}else{//单Y轴数量级时
				xml = FusionChartsUtil.Muti_Series_Line2D(xAxisList, rightAxisValues);
				xml = xml.replace("showValues=\"1\"", "showValues=\"0\"");
				xml = "LINE2D:"+xml;
			}
			return  new ContentResult(xml);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return new ContentResult("");
	}
	
	
	/**厂商、游戏级联
	 * @return
	 */
	@Path("getgames")
	@POST
	@GET
	public ActionResult getgames() {
		return new ActionResult() {
			@Override
			public void render(BeatContext beat)  {
				HttpServletRequest request = beat.getRequest();
				HttpServletResponse response = beat.getResponse();		
				String companyId = request.getParameter("companyId");
				try {
					List<WanGame> gameList =  webGameService.getGameList(Integer.parseInt(companyId));
					JSONObject json = new JSONObject();
					json.accumulate("items", gameList);
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(json.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
	
	
	/**厂商、游戏、服务器 级联
	 * @return
	 */
	@Path("getservers")
	@POST
	@GET
	public ActionResult getservers() {
		return new ActionResult() {
			@Override
			public void render(BeatContext beat)  {
				HttpServletRequest request = beat.getRequest();
				HttpServletResponse response = beat.getResponse();		
				String companyId = request.getParameter("companyId");
				String gameId = request.getParameter("gameId");
				
				try {
					List<WanService> serviceList =  webGameService.getServiceList(Long.parseLong(companyId) ,Long.parseLong(gameId) );
					JSONObject json = new JSONObject();
					json.accumulate("items", serviceList);
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(json.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
		
	
}